package Dome429;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

//接收方
public class UdpReceiver {

    public static void main(String[] args) {
        //声明数据包对象
        DatagramPacket dp = null;
        //声明数据包套接字对象
        DatagramSocket ds = null;
        //创建Scanner对象
        Scanner input = new Scanner(System.in);

        try {
            ds = new DatagramSocket(8989);
            System.out.println("服务器已开启，可以在线咨询了。");

            byte[] buf = new byte[1024];

            while(true) {
                //准备空数据包
                dp = new DatagramPacket(buf, buf.length);
                System.out.println("receive1");
                //接收数据
                ds.receive(dp);
                System.out.println("receive2");
                //数据包解析为字符串
                String mess = new String(dp.getData(), 0, dp.getLength());
                InetAddress ia = dp.getAddress();
                System.out.println(ia.getHostAddress() + ":" + dp.getPort() + "说：" + mess);


                //回应
                mess = input.nextLine();
                byte[] data = mess.getBytes();
                //getSocketAddress() 发送方IP地址+端口号。
                dp = new DatagramPacket(data,data.length,dp.getSocketAddress());
                ds.send(dp);
            }


        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }


    }


}

